const comment = require("../dao/commentDao");
const validate = require("validate.js");
const blog = require("../dao/blogDao");
const { ValidationError } = require("../utils/errors");
const { getAvatarPath } = require("../utils/tool");
//文章id验证
validate.validators.blogIdVerify = async (id) => {
  const result = await blog.getBlog(id);
  if (result) {
    return;
  } else {
    return "blogId Is Not Exist";
  }
};

// 添加评论
const addComment = async (info) => {
  info.createDate = Date.now();
  info.avatar = await getAvatarPath();
  const rule = {
    nickname: {
      presence: {
        allowEmpty: false,
      },
      type: "string",
    },
    content: {
      presence: {
        allowEmpty: false,
      },
      type: "string",
    },
    createDate: {
      presence: {
        allowEmpty: false,
      },
      type: "integer",
    },
    avatar: {
      presence: {
        allowEmpty: false,
      },
      type: "string",
    },
    blogId: {
      presence: {
        allowEmpty: false,
      },
      type: "integer",
      blogIdVerify: true,
    },
  };
  try {
    await validate.async(info, rule);
    const result = await comment.addComment(info);
    await blog.addCommentNumber(result.blogId); //评论数量自增
    delete result.blogId;
    return result;
  } catch (error) {
    console.log(error);
    throw new ValidationError("数据验证失败");
  }
};

//删除评论
const deleteComment = async (id) => {
  const { blogId } = await comment.deleteComment(id);
  await blog.reduceComentNumber(blogId);

  return true;
};

//分页获取评论
const getCommentList = async (
  page = 1,
  limit = 10,
  keyword = "",
  blogId = -1
) => {
  const info = { page, limit, blogId };

  const rule = {
    page: {
      presence: {
        allowEmpty: false,
      },
      type: "integer",
    },
    limit: {
      presence: {
        allowEmpty: false,
      },
      type: "integer",
    },
    blogId: {
      presence: {
        allowEmpty: false,
      },
      type: "integer",
    },
  };
  try {
    await validate.async(info, rule);
    const result = await comment.getCommentList(page, limit, keyword, blogId);
    return result;
  } catch (error) {
    console.log(error);
    throw new ValidationError("数据验证失败");
  }
};

module.exports = {
  addComment,
  deleteComment,
  getCommentList,
};
